<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="state.editor.htmlVal"
      :defaultConfig="editorConfig"
      placeholder="请输入内容"
      mode="default"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts" name="activityContent">
import { ElMessage, FormInstance } from 'element-plus';
import { useUpload } from '/@/hooks/use-upload';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { reactive, ref, shallowRef, onBeforeUnmount } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

import { DomEditor } from '@wangeditor/editor';

const { action, headers } = useUpload();

const formRef = ref<FormInstance>();
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const toolbarConfig: any = {
  excludeKeys: ['codeBlock', 'todo']
};
const editorConfig: any = { placeholder: '请输入内容', MENU_CONF: {} };

editorConfig.MENU_CONF['uploadImage'] = {
  server: action,
  timeout: 60 * 1000, // 5s
  fieldName: 'file',
  metaWithUrl: true, // join params to url
  headers: headers,
  maxFileSize: 10 * 1024 * 1024, // 10M
  base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb
  onBeforeUpload(file: any) {
    console.log('onBeforeUpload', file);
    return file; // will upload this file
    // return false // prevent upload
  },
  onSuccess(file: any, res: any) {
    console.log('onSuccess', file, res);
  },
  onFailed(file: any, res: any) {
    alert(res.message);
    console.log('onFailed', file, res);
  },
  onError(file: any, err: any, res: any) {
    alert(err.message);
    console.error('onError', file, err, res);
  },
  customInsert(res: any, insertFn: any) {
    console.log('custom insert',  res)
    if (res.code === 200) {
      const { url, origin_name: alt } = res.data
      if (!url) throw new Error(`Image url is empty`);
      insertFn(url, alt, url);
    } else {
      throw new Error(res.message);
    }
  }
};

const state = reactive({
  editor: {
    htmlVal: ''
  },
  tempId: null
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 暴露变量
defineExpose({
  validate: () => {
    return new Promise((resovle, reject) => {
      if (!state.editor.htmlVal) {
        ElMessage.error('请输入内容');
        reject(new Error('不能为空'));
      } else {
        resovle(state.editor.htmlVal)
      }
    })
  },
  getValue() {
    return state.editor.htmlVal
  },
  setValue(value: string) {
    state.editor.htmlVal = value
  }
});
</script>
